#include "si12_exti.h"
#include <string.h>
#include "as608_task.h"

u8 flag ;
extern u8 data_buf[4];
void MyExti1_init(void)
{
    EXTI_InitTypeDef EXTI_InitStructure;		//EXTIx中断线配置
    NVIC_InitTypeDef NVIC_InitStructure;		//EXTIx中断向量配置
    GPIO_InitTypeDef GPIO_InitStructure;


    //配置按键引脚为下降沿中断
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO|RCC_APB2Periph_GPIOB,ENABLE);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_Init(GPIOB, &GPIO_InitStructure);

    //绑定中断线
    GPIO_EXTILineConfig(GPIO_PortSourceGPIOB,GPIO_PinSource5);

    EXTI_InitStructure.EXTI_Line=EXTI_Line5;
    EXTI_InitStructure.EXTI_Mode=EXTI_Mode_Interrupt;
    EXTI_InitStructure.EXTI_Trigger=EXTI_Trigger_Falling;
    EXTI_InitStructure.EXTI_LineCmd=ENABLE;
    EXTI_Init(&EXTI_InitStructure);

    NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 5;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_Init(&NVIC_InitStructure);

}

uint8_t temp[3];
uint8_t x_tp;

void EXTI9_5_IRQHandler(void)
{
    uint8_t i,j;
    if (RESET != EXTI_GetITStatus(EXTI_Line5)&&flag == 0)
    {
//清除中断标记
        SI12_ReadData();
        x_tp = 0 ;
        for(i=0; i<3; i++)
        {
            for(j=0; j<4; j++)
            {
                if(((data_buf[i]>>(2*j))&0x03)!= 0)
                {
                    x_tp++;
                    flag = (i*4+j)+1;
                }
            }
        }

//两个以上按键，清除flag ，保存数据以便松开按键但没有全部松开时比对
        if(x_tp>1)
        {

            memcpy(temp,data_buf,3);
            flag = 0;

        }

//按键松开，清空按下的缓冲数据
        else if(x_tp == 0)
        {
            memset(temp,0,3);

        }

        /*
        只有一个按键按下，判断此次是否为按键松下时的中断
        若是flag清零
        不是flag正常输出
        */
        else
        {
            if(temp[0] != 0)
            {
                for(i=0; i<3; i++)
                {
                    for(j=0; j<4; j++)
                    {
                        if(((temp[i]>>(2*j))&0x03)!= 0)
                        {
                            if(flag == i*4+j+1)
                            {
                                flag = 0;
                            }
                        }
                    }
                }
            }
        }
        if(flag == 12)
        {
          while_flag = 0;
        }
    }
    EXTI_ClearITPendingBit(EXTI_Line5);
		
}

